#!/usr/bin/env python
# Get latest wallpaper from web and set it as desktop wallpaper.
#
import sys
import os
import random
import getopt
import time
import logging

from logger import logger
from wallpaper_modules import *
from configs import config

DEFAULT_MODULE = 3

def usage():
    print "Usage:"
    print "%s [options] index" % (sys.argv[0])
    print "\tindex:\t\tThe index of module to run"
    print "Options:"
    print "\t-d:\t\tEnable debug mode"
    print "\t-l:\t\tList all modules"
    print "\t-r:\t\tRun random modules"
    print "\t-w num:\t\tWait num of seconds before download image"
    print "\t-h:\t\tPrint this help message"

def main():
#    # Import Psyco if available
#    try:
#        import psyco
#        psyco.full()
#    except ImportError:
#        pass

    random.seed()

    wallpaper_modules = WallPaperModules()

    try:
        opts, args = getopt.getopt(sys.argv[1:], "w:dlrh?", ["help"])
    except getopt.error, v:
        print v
        usage()
        sys.exit(1)

    # Default args
    index = DEFAULT_MODULE
    delay = 0

    for opt, arg in opts:
        if opt in ('-h', '-?', '--help'):
            usage()
            sys.exit(0)
        elif opt == "-d":
            logger.setLevel(logging.DEBUG)
        elif opt == "-l":
            wallpaper_modules.list_modules()
            sys.exit(0)
        elif opt == "-r":
            index = random.randint(1, wallpaper_modules.num_of_modules())
        elif opt == "-w":
            try:
                delay = int(arg)
            except ValueError:
                usage()
                sys.exit(1)

    if len(args):
        try:
            index = int(args[0])
        except ValueError:
            usage()
            sys.exit(1)

    # Wait for some time if requested, usually useful for change wallpaper at system starting up
    time.sleep(delay)

    logger.info("Selected module #%d" % index)
    logger.debug("With Config:\n%s" % config)

    if index <= 0 or index > wallpaper_modules.num_of_modules():
        logger.error("Module index out of range. Please select between 1 - %d" % (wallpaper_modules.num_of_modules()))
    else:
        try:
            wallpaper_modules.run_module(index)
        except:
            import traceback
            logger.error("Error in running wallpaper module:\n%s" % traceback.format_exc())
            raise

if __name__ == '__main__':
    main()
